package com.rainyun.rcmc.own.bukkit.controller;

import com.rainyun.rc.command.ConvertException;
import com.rainyun.rc.command.annotation.BeanCmd;
import com.rainyun.rc.config.NodeConfig;
import com.rainyun.rc.ioc.Beanzy;
import com.rainyun.rc.util.RainF;
import com.rainyun.rcmc.bukkit.BukCmdPath;
import com.rainyun.rcmc.bukkit.annotation.Buk;
import com.rainyun.rcmc.own.bukkit.biz.BizCommon;
import com.rainyun.rcmc.own.bukkit.main.BukRainCore;
import com.rainyun.rcmc.own.common.BeanRc;
import com.rainyun.rcmc.own.config.RcCmdAttr;
import com.rainyun.rcmc.own.config.RcLang;
import com.rainyun.rcmc.own.config.RcPerm;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;

@Buk
@BeanCmd("raincore")
@RcCmdAttr(
		perm = RcPerm.RC_Admin,
		help = "&8 v{version} by Akr_on",
		alias = {"rc"}
)
public class CmdRC extends BukCmdPath{

	@Beanzy
	static BukRainCore plugin;
	@BeanRc(BeanRc.BeansRc.NodeConf)
	static NodeConfig<?> ncf;
	@Beanzy
	static BizCommon bizCommon;

	@Override
	public void init() {

		this.addTabExec("nmscomp",(sd,path,ca)->{
			File dir = plugin.getDataFolder().getParentFile();
			String[] list = dir.list((dir1, name) -> {
				if(name.endsWith(".jar")&&!RainF.inArray(ca.getArgs(),name))
					return true;
				return false;
			});
			return new ArrayList<>(Arrays.asList(list));
		});
		this.addCheckExec("nmscomp",(sd,ca)->{
			String[] names = Arrays.copyOfRange(ca.getArgs(),1,ca.getArgs().length);
			File[] files = new File[names.length];
			for(int i=0;i<names.length;i++){
				String name = names[i];
				File dir = plugin.getDataFolder().getParentFile();
				File file = new File(dir, name);
				if(file.exists()){
					if(file.getName().endsWith(".jar")){
						files[i]=file;
						continue;
					}else sendWithPrefix(sd,name+"不是插件jar文件");
				}else sendWithPrefix(sd,name+"不存在");
				return false;
			}
			ca.set("file",files);
			return true;
		});

	}

	@Override
	public void sendWithPrefix(CommandSender sd, String msg) {
		bizCommon.sendWithPrefix(sd,msg);
	}
	@Override
	public void sendMsg(CommandSender sd, String msg) {
		bizCommon.sendMsg(sd,msg);
	}

	@Override
	public Plugin getPlugin() {
		return plugin;
	}

	@Override
	public <T> T getAttr(Object name) {
		T attr = null;
		//前后缀设置
		if(name.equals("help_prefix"))
			attr=ncf.get(RcLang.cmd_help_prefix);
		else if(name.equals("help_suffix"))
			attr=ncf.get(RcLang.cmd_help_suffix);
		else attr=super.getAttr(name);

		if(attr!=null&&"raincore".equals(this.getName())&&"help".equals(name))
			attr= (T) attr.toString().replace("{version}",plugin.getDescription().getVersion());
		return attr;
	}

	@Override
	public void handleExecError(CommandSender sd, Throwable e) {
		e.printStackTrace();
		bizCommon.sendWithPrefix(sd,ncf.get(RcLang.error));
	}
}









